

<!DOCTYPE html>
<html lang="zh-CN">

<head><meta name="generator" content="Hexo 3.9.0">
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Fragment返回栈预备篇 OnBackPressedDispatcher - 杨云召 | 博客</title>
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
  <meta name="google" content="notranslate">

  
  
  <meta name="description" content="Fragment 处理返回键的新姿势。


这两天在准..."> 
  
  <meta name="author" content="杨云召（Flywith24）"> 

  
    <link rel="icon" href="/images/icons/favicon-16x16.png" type="image/png" sizes="16x16">
  
  
    <link rel="icon" href="/images/icons/favicon-32x32.png" type="image/png" sizes="32x32">
  
  
    <link rel="apple-touch-icon" href="/images/icons/apple-touch-icon.png" sizes="180x180">
  
  
    <meta rel="mask-icon" href="/images/icons/stun-logo.svg" color="#333333">
  
  
    <meta rel="msapplication-TileImage" content="/images/icons/favicon-144x144.png">
    <meta rel="msapplication-TileColor" content="#000000">
  

  <link rel="stylesheet" href="/css/style.css">

  
  <link rel="stylesheet" href="//at.alicdn.com/t/font_1445822_hhodbqn7tit.css">
  

  
  
  <link rel="stylesheet" href="https://cdn.bootcss.com/fancybox/3.5.7/jquery.fancybox.min.css">
  

  
  
  <link rel="stylesheet" href="https://cdn.bootcss.com/highlight.js/9.18.1/styles/xcode.min.css">
  

  <script>
    var CONFIG = window.CONFIG || {};
    var ZHAOO = window.ZHAOO || {};
    CONFIG = {
      isHome: false,
      fancybox: true,
      pjax: false,
      lazyload: {
        enable: true,
        loadingImage: '/images/theme/loading.gif',
      },
      donate: {
        enable: true,
        alipay: 'https://gitee.com/flywith24/Album/raw/master/img/20201015113301.jpg',
        wechat: 'https://gitee.com/flywith24/Album/raw/master/img/20201015112814.png'
      },
      motto: {
        api: '',
        default: '不人云亦云，只求接近真相.'
      },
      galleries: {
        enable: true
      },
      fab: {
        enable: true,
        alwaysShow: false
      },
      carrier: {
        enable: true
      },
      daovoice: {
        enable: true
      }
    }
  </script>

  

  
</head></html>
<body class="lock-screen">
  <div class="loading"></div>
  


<nav class="navbar">
  <div class="left"></div>
  <div class="center">Fragment返回栈预备篇 OnBackPressedDispatcher</div>
  <div class="right">
    <i class="iconfont iconmenu j-navbar-menu"></i>
  </div>
</nav>

  <nav class="menu">
  <div class="menu-wrap">
    <div class="menu-close">
      <i class="iconfont iconbaseline-close-px"></i>
    </div>
    <ul class="menu-content">
      
      
      
      
      <li class="menu-item"><a href="/ " class="underline"> 首页</a></li>
      
      
      
      
      <li class="menu-item"><a href="/archives " class="underline"> 归档</a></li>
      
      
      
      
      <li class="menu-item"><a href="/tags " class="underline"> 标签</a></li>
      
      
      
      
      <li class="menu-item"><a href="/categories " class="underline"> 分类</a></li>
      
      
      
      
      <li class="menu-item"><a href="/about " class="underline"> 关于</a></li>
      
    </ul>
    <div class="menu-copyright"><p>Copyright© 2017 - 2020 ❤️ Flywith24</p></div>
  </div>
</nav>
  <main id="main">
  <div class="container" id="container">
    <article class="article">
  <div class="wrap">
    <section class="head">
  <img   class="lazyload" data-original="https://gitee.com/flywith24/Album/raw/master/img/20201015094956.png" src=""  draggable="false">
  <div class="head-mask">
    <h1 class="head-title">Fragment返回栈预备篇 OnBackPressedDispatcher</h1>
    <div class="head-info">
      <span class="post-info-item"><i class="iconfont iconcalendar"></i>三月 14, 2020</span
        class="post-info-item">
      
      <span class="post-info-item"><i class="iconfont iconfont-size"></i>2397</span>
    </div>
  </div>
</section>
    <section class="main">
      <section class="content">
        <blockquote>
<p>这两天在准备写 fragment 返回栈的文章，但是发现必须先介绍一下 OnBackPressedDispatcher ，所以这是一篇介绍 what 的文章，喜欢一手资料的可以移步 <a href="https://developer.android.google.cn/reference/kotlin/androidx/activity/OnBackPressedDispatcher" target="_blank" rel="noopener">官方文档</a></p>
</blockquote>
<h2 id="系列文章"><a href="#系列文章" class="headerlink" title="系列文章"></a>系列文章</h2><blockquote>
<p><a href="https://juejin.im/post/5e567ee1518825494466a938" target="_blank" rel="noopener">【背上Jetpack】Jetpack 主要组件的依赖及传递关系</a><br></p>
<p><a href="https://juejin.im/post/5e5a0c316fb9a07cd248d29e" target="_blank" rel="noopener">【背上Jetpack】AdroidX下使用Activity和Fragment的变化</a><br></p>
<p><a href="https://juejin.im/post/5e5cd8686fb9a07cbc269d10" target="_blank" rel="noopener">【背上Jetpack之Fragment】你真的会用Fragment吗？Fragment常见问题以及androidx下Fragment的使用新姿势</a><br></p>
<p><a href="https://juejin.im/post/5e67523551882549003d2c4f" target="_blank" rel="noopener">【背上Jetpack之Fragment】从源码角度看 Fragment 生命周期 AndroidX Fragment1.2.2源码分析</a></p>
</blockquote>
<h2 id="When"><a href="#When" class="headerlink" title="When"></a>When</h2><p><code>OnBackPressedDispatcher</code> 在 <code>androidx activity 1.0.0</code> 加入，旨在处理返回逻辑。您不仅可以获得在 <code>Activity</code> 之外处理返回键的便捷方式。 根据您的需要，您可以在任意位置定义 <code>OnBackPressedCallback</code>，使其可复用，或根据应用程序的架构进行任何操作。 您不再需要重写<code>Activity</code> 中的 <code>onBackPressed</code> 方法，也不必提供自己的抽象的来实现需求的代码。</p>
<p><img class="lazyload" data-original="https://user-gold-cdn.xitu.io/2020/3/14/170d4a399942581f?w=1778&h=1246&f=png&s=339228" src="/2020/03/14/Jetpack-OnBackPressedDispatcher/gif;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQImWNgYGBgAAAABQABh6FO1AAAAABJRU5ErkJggg==" alt="OnBackPressedDispatcher"></p>
<h2 id="What"><a href="#What" class="headerlink" title="What"></a>What</h2><p><code>ComponentActivity</code> 是 <code>FragmentActivity</code> 和 <code>AppCompatActivity</code> 的基类，它使您可以通过使用其 <code>OnBackPressedDispatcher</code>（可以通过调用 <code>getOnBackPressedDispatcher()</code> ）来控制返回按钮的行为。</p>
<p><img class="lazyload" data-original="https://user-gold-cdn.xitu.io/2020/3/14/170d4a9d225a9575?w=2168&h=1150&f=png&s=238889" src="/2020/03/14/Jetpack-OnBackPressedDispatcher/gif;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQImWNgYGBgAAAABQABh6FO1AAAAABJRU5ErkJggg==" alt="ComponentActivity-onBackPressed"></p>
<p><code>OnBackPressedDispatcher</code> 控制如何将返回按钮事件分配给一个或多个<code>OnBackPressedCallback</code> 对象。 <code>OnBackPressedCallback</code> 的构造函数将布尔值用于初始启用状态。 仅当启用了回调（即 <code>isEnabled()</code> 返回true）时，调度程序才会调用回调的<code>handleOnBackPressed()</code> 来处理返回按钮事件。 您可以通过调用 <code>setEnabled()</code> 来更改启用状态。</p>
<p>回调是通过 <code>addCallback</code> 方法添加的。 强烈建议使用采用 LifecycleOwner 的<code>addCallback()</code> 方法。 这样可以确保仅在 LifecycleOwner 为 Lifecycle.State.STARTED 时才添加<code>OnBackPressedCallback</code>。 当关联的 LifecycleOwner 被销毁时，该 activity 会删除已注册的回调，以防止内存泄漏，并使其适用于寿命比该 <code>activity</code> 短的 <code>fragment</code> 或其他生命周期所有者。</p>
<p>下面是一个示例</p>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><code class="hljs kotlin"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyFragment</span> : <span class="hljs-type">Fragment</span></span>() &#123;<br><br>    <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onCreate</span><span class="hljs-params">(savedInstanceState: <span class="hljs-type">Bundle</span>?)</span></span> &#123;<br>        <span class="hljs-keyword">super</span>.onCreate(savedInstanceState)<br><br>        <span class="hljs-comment">//此 callback 仅当 MyFragment 至少是 Started 状态下调用</span><br>        <span class="hljs-keyword">val</span> callback = requireActivity().onBackPressedDispatcher.addCallback(<span class="hljs-keyword">this</span>) &#123;<br>            <span class="hljs-comment">//拦截返回事件</span><br>        &#125;<br><br>        <span class="hljs-comment">//此 callback 可以在这里或者上面的 lambda 中开启和关闭</span><br>    &#125;<br>    ...<br>&#125;<br></code></pre></td></tr></table></figure>

<p>您可以通过 <code>addCallback()</code> 提供多个回调。 这样做时，将按照添加回调的相反顺序调用回调，即最后添加的回调是第一个给予处理返回按钮事件的机会的回调。 例如，如果您依次添加了三个分别名为1、2和3的回调，则将分别以3、2和1的顺序调用它们。</p>
<p>回调遵循“责任链”模式。 仅当未启用前一个回调时，才调用链中的每个回调。 这意味着在前面的示例中，仅当未启用回调3时，才会调用回调2。 仅当未启用回调2时，才调用回调1，依此类推。</p>
<p>请注意，通过 <code>addCallback()</code> 添加回调时，直到 LifecycleOwner 进入Lifecycle.State.STARTED 状态，才将回调添加到责任链中。</p>
<p>强烈建议更改 <code>OnBackPressedCallback</code> 的启用状态以进行临时更改(即更改 isEnabled 的值)，因为它可以保持上述顺序，如果您在多个不同的嵌套生命周期所有者上注册了回调，这尤其重要。</p>
<p>但是，如果要完全删除 <code>OnBackPressedCallback</code>，则应调用 remove()。 但是，这通常不是必需的，因为在销毁关联的 <code>LifecycleOwner</code> 时会自动删除其回调。</p>
<h2 id="Activity-onBackPressed"><a href="#Activity-onBackPressed" class="headerlink" title="Activity onBackPressed()"></a>Activity onBackPressed()</h2><p>如果您使用 <code>onBackPressed()</code> 处理返回按钮事件，建议您改用 <code>OnBackPressedCallback</code> 。 但是，如果您无法进行此更改，则适用以下规则：</p>
<ul>
<li><p>当您调用 <code>super.onBackPressed()</code> 时，将通过 <code>addCallback</code> 注册的所有回调。</p>
</li>
<li><p>无论 <code>OnBackPressedCallback</code> 的任何注册实例，始终会调用 <code>onBackPressed</code>。</p>
</li>
</ul>
<h2 id="Demo"><a href="#Demo" class="headerlink" title="Demo"></a>Demo</h2><p>关于 fragment 返回栈的 demo 已经写好了，感兴趣的小伙伴可以 <a href="https://github.com/Flywith24/Flywith24-Fragment-Demo" target="_blank" rel="noopener">在这</a> 找到它。</p>
<p>我们下一篇再见。</p>
<hr>
<h2 id="关于我"><a href="#关于我" class="headerlink" title="关于我"></a>关于我</h2><hr>
<p>我是 <a href="https://flywith24.gitee.io/">Fly_with24</a></p>
<ul>
<li><p><a href="https://juejin.im/user/57c7f6870a2b58006b1cfd6c" target="_blank" rel="noopener">掘金</a></p>
</li>
<li><p><a href="https://www.jianshu.com/u/3d5ad6043d66" target="_blank" rel="noopener">简书</a></p>
</li>
<li><p><a href="https://github.com/Flywith24" target="_blank" rel="noopener">Github</a></p>
</li>
</ul>
      </section>
      <section class="extra">
        
        <ul class="copyright">
  
  <li><strong>本文作者：</strong>杨云召（Flywith24）</li>
  <li><strong>本文链接：</strong><a href="https://flywith24.gitee.io/2020/03/14/Jetpack-OnBackPressedDispatcher/index.html">https://flywith24.gitee.io/2020/03/14/Jetpack-OnBackPressedDispatcher/index.html</a></li>
  <li><strong>版权声明：</strong>本博客所有文章均采用<a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh"
      rel="external nofollow" target="_blank"> BY-NC-SA </a>许可协议，转载请注明出处！</li>
  
</ul>
        
        
        <section class="donate">
  <div class="qrcode">
    <img   class="lazyload" data-original="https://gitee.com/flywith24/Album/raw/master/img/20201015113301.jpg" src="" >
  </div>
  <div class="icon">
    <a href="javascript:;" id="alipay"><i class="iconfont iconalipay"></i></a>
    <a href="javascript:;" id="wechat"><i class="iconfont iconwechat-fill"></i></a>
  </div>
</section>
        
        
  <ul class="tag-list"><li class="tag-list-item"><a class="tag-list-link" href="/tags/Jetpack/">Jetpack</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/MVVM/">MVVM</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/androidx/">androidx</a></li></ul>

        
<nav class="nav">
  
    <a href="/2020/03/16/Jetpack-fragment-back-stack/"><i class="iconfont iconleft"></i>从源码的角度看 Fragment 返回栈</a>
  
  
    <a href="/2020/03/10/Jetpack-fragment-lifecycle/">从源码角度看Fragment的启动流程及生命周期 基于AndroidX Fragment1.2.2<i class="iconfont iconright"></i></a>
  
</nav>

      </section>
      
      <section class="comments">
  
  <div class="btn" id="comments-btn">查看评论</div>
  
  
<div id="valine"></div>
<script defer src="//unpkg.com/valine/dist/Valine.min.js"></script>
<script>
  window.onload = function () {
    var loadValine = function () {
      new Valine({
        el: '#valine',
        app_id: "SHA3gzCcxFlqaPcGRnX4UgET-gzGzoHsz",
        app_key: "OYo7ITS4AzTvBUvb1yIY8oaf",
        placeholder: "期待你的留言",
        avatar: "mp",
        pageSize: "10",
        lang: "zh-CN",
      });
    }
    if ( true ) {
      $("#comments-btn").on("click", function () {
        $(this).hide();
        loadValine();
      });
    } else {
      loadValine();
    }
  };
</script>

</section>
      
    </section>
  </div>
</article>
  </div>
</main>
  <footer class="footer">
  <div class="footer-social">
    
    
    
    
    
    <a href="tencent://message/?Menu=yes&uin=1032367864 " target="_blank" onMouseOver="this.style.color= '#12B7F5'"
      onMouseOut="this.style.color='#33333D'">
      <i class="iconfont footer-social-item  iconQQ "></i>
    </a>
    
    
    
    
    
    <a href="javascript:; " target="_blank" onMouseOver="this.style.color= '#8bc34a'"
      onMouseOut="this.style.color='#33333D'">
      <i class="iconfont footer-social-item  iconwechat-fill "></i>
    </a>
    
    
    
    
    
    <a href="https://flywith24.gitee.io/about/ " target="_blank" onMouseOver="this.style.color= '#d32f2f'"
      onMouseOut="this.style.color='#33333D'">
      <i class="iconfont footer-social-item  iconheart "></i>
    </a>
    
    
    
    
    
    <a href="https://github.com/Flywith24 " target="_blank" onMouseOver="this.style.color= '#24292E'"
      onMouseOut="this.style.color='#33333D'">
      <i class="iconfont footer-social-item  icongithub-fill "></i>
    </a>
    
    
    
    
    
    <a href="mailto:youngyunzhao@163.com " target="_blank" onMouseOver="this.style.color='#FFBE5B'"
      onMouseOut="this.style.color='#33333D'">
      <i class="iconfont footer-social-item  iconmail"></i>
    </a>
    
  </div>
  <div class="footer-copyright"><p>Copyright© 2017 - 2020 ❤️ Flywith24</p></div>
</footer>
  
      <div class="fab fab-plus">
    <i class="iconfont iconplus"></i>
  </div>
  
  <div class="fab fab-daovoice">
    <i class="iconfont iconcomment"></i>
  </div>
  
  <div class="fab fab-up">
    <i class="iconfont iconcaret-up"></i>
  </div>
  
<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"debug":false,"model":{"jsonPath":"/live2dw/assets/shizuku.model.json"},"display":{"position":"left","width":150,"height":300},"mobile":{"show":"tfalse"},"log":false});</script></body>

<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>




<script src="https://cdn.bootcdn.net/ajax/libs/jquery.lazyload/1.9.1/jquery.lazyload.min.js"></script>




<script src="https://cdn.bootcss.com/fancybox/3.5.7/jquery.fancybox.min.js"></script>




<script src="/js/utils.js"></script>
<script src="/js/modules.js"></script>
<script src="/js/zui.js"></script>
<script src="/js/script.js"></script>




<script>
  (function (i, s, o, g, r, a, m) {
    i["DaoVoiceObject"] = r;
    i[r] = i[r] || function () {
      (i[r].q = i[r].q || []).push(arguments)
    }, i[r].l = 1 * new Date();
    a = s.createElement(o), m = s.getElementsByTagName(o)[0];
    a.async = 1;
    a.src = g;
    a.charset = "utf-8";
    m.parentNode.insertBefore(a, m)
  })(window, document, "script", ('https:' == document.location.protocol ? 'https:' : 'http:') +
    "//widget.daovoice.io/widget/0f81ff2f.js", "daovoice")
  daovoice('init', {
    app_id: "7785620b"
  }, {
    launcher: {
      disableLauncherIcon: true,
    },
  });
  daovoice('update');
</script>



<script>
  (function () {
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
      bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
    } else {
      bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
  })();
</script>


<script>
  var _hmt = _hmt || [];
  (function () {
    var hm = document.createElement("script");
    hm.src = "https://hm.baidu.com/hm.js?4c204d8bc027a0455b5fc642ac334ca8";
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(hm, s);
  })();
</script>










</html>